import Room from "./Room";
import LanguageMng from "../Managers/LanguageMng";
import GameLogicUtilTs from "../Utils/GameLogicUtilTs";
import RoomTypes from "../Static/RoomTypes";

export default class DealRoom extends Room {

    //赌注
    bet = 0;
    //用于记分板
    scores = [];

    en_class() {
        return 'DealRoom';
    }

    onCreate(){
        this.info = cc.gg.enumConfig.getRoomInfoById(cc.gg.enumConfig.RoomType.POOL,this.mode)
    }
    onDestroy(){
        super.onDestroy()
        cc.find("Canvas").emit("game_room_destroy")
        // if(GameLogicUtilTs.wantQuitRoom){
        //     GameLogicUtilTs.wantQuitRoom = false
        //     cc.find("Canvas").emit("game_room_destroy")
        // }
    }

    initRoom(gameMgr){
        // cc.log("穿件Deal房间：",{id:this.mode,type:RoomTypes.DEAL})
        super.initRoom(gameMgr)

        let oriScores = this.scores
        cc.log("初始化scores")
        this.scores = []

        cc.logfl("初始化得分记录scores",oriScores)
        for(let i=0;i<oriScores.length;i++){
            let netScoreObj = oriScores[i]
            if(!this.scores[netScoreObj.id]){
                this.scores[netScoreObj.id] = {}
                this.scores[netScoreObj.id].scores = []
            }

            this.scores[netScoreObj.id].scores = netScoreObj.scores
        }
    }

    openRoom(){
        cc.logfl("open room")
        let mode = this.mode
        let roomMode = cc.gg.enumConfig.RoomMode
        let modeBase = mode & 0x0f0
        if(modeBase === roomMode.BASE_VALUE_2){
            cc.director.loadScene('TwoPlayerGame',function () {
                // if(this.state === 0 && this.timer_cd) cc.find("Canvas/UIManager").emit("ui_game_count_down_start",this.timer_cd)
                // cc.find("Canvas/UIManager").emit("ui_show_deal_waitting_string","Waitting for other players...")
            }.bind(this))
        }else if(modeBase === roomMode.BASE_VALUE_6){
            cc.director.loadScene('SixPlayerGame',function () {
                // if(this.state === 0 && this.timer_cd) cc.find("Canvas/UIManager").emit("ui_game_count_down_start",this.timer_cd)
                if(this.state === 0 && this.timer_cd) cc.find("Canvas/UIManager").emit("ui_show_deal_waitting_string",LanguageMng.getSentence(183))
            }.bind(this))
        }
    }

    onCreate(){
        super.onCreate()
        this.info = cc.gg.enumConfig.getRoomInfoById(cc.gg.enumConfig.RoomType.DEAL,this.mode)
        this.baseScore = this.info.r_top * 80
        cc.log("Deal初始化basescore", this.baseScore)
    }

    onResult(data){
        super.onResult(data)
        cc.logws("DealRoom 收到result消息：",data)

        let resultArray = data[0]
        resultArray.sort((a, b) => b.score - a.score)

        let idx = 0
        for(let i=0;i<resultArray.length;i++){
            let obj = resultArray[i]
            if(obj.id === cc.gg.dataMgr.getPlayerGameId()){
                idx = i
                break
            }
        }

        let rankStr = ""
        if(idx === 0){
            rankStr = "1st"
        }else if(idx === 1){
            rankStr = "2nd"
        }else {
            rankStr = (idx+1) + "th"
        }

        let gameName = ""
        if(cc.gg.dataMgr.room.info.e_fee === 0){
            gameName = "Practise"
        }else {
            gameName = cc.gg.gameDataUtil.getStringOfRupee(cc.gg.dataMgr.room.info.e_fee)
        }

        let str1 = "You have finished the game in "
        let str2 = " position.Would you like to player another "
        let str3 = "-Deals Rummy game?"
        let contentStr = str1+rankStr+str2+gameName+str3

        setTimeout(function()
        {
            cc.find("Canvas/UIManager").getComponent("GameUIMgr")._showDealBoard()
            this.scores = []
        }.bind(this),1000)

        setTimeout(function()
        {
            let title = LanguageMng.getSentence(3)
            let positiveStr = "OK"
            let passiveStr = "Play Again"
            cc.gg.toastMgr.showDialogOneButton(title,positiveStr,contentStr,
                function () {
                    let user = cc.gg.dataMgr.getPlayerUser()
                    if(user) user.leave()
                    cc.gg.toastMgr.removeDialog()
                }.bind(this)
            )
        }.bind(this),2000)
    }

    onReport(scores){
        cc.gg.gameDataUtil.resultJustNow = false
        scores = scores[0]

        if(!cc.gg.gameDataUtil.receiveFinish){
            let showScoreWhenWaiting = true
            cc.find("Canvas/UIManager").emit("ui_init_deal_info_board",null,null,showScoreWhenWaiting)
        }

        for(let i=0;i<scores.length;i++){
            let obj1 = scores[i]
            let id = obj1.id
            let score = obj1.score

            let userObj = cc.gg.dataMgr.getUser(id)
            if(userObj) {
                userObj.score += score
                cc.find("Canvas").emit("ui_update_head_score",id,userObj.score)
            }

            cc.find("Canvas/UIManager").emit("ui_update_dealinfo_scores",obj1.id,score,userObj.score,true)
            // cc.find("Canvas/UIManager").emit("ui_update_deal_info_board",{id:obj1.id,score:obj1.score,totalScore:userObj.score})
        }
        cc.find("Canvas/UIManager").emit("ui_show_score",false)
        // cc.gg.emitEvent("dealinfo_start_count_down",this.timer_cd)

        //更新计分板数据，当再次打开计分板会看到更新过的数据
        this.updateScores(scores)
        this.updateWinner(scores)
    }

    updateScores(scores){
        cc.log("daelScores增加记录：",scores)
        for(let i=0;i<scores.length;i++){
            let netScoreObj = scores[i]
            if(!this.scores[netScoreObj.id]){
                this.scores[netScoreObj.id] = {}
                this.scores[netScoreObj.id].scores = []
            }

            this.scores[netScoreObj.id].scores.push(netScoreObj.score)
        }
        cc.log("ddddScores增加记录完毕：",this.scores)
    }

    //不改变user的原本分数
    // getTotalScore(taruid){
    //     if(!this.scores)
    //         return 0
    //
    //     for(let key in this.scores){
    //         let hisObj = this.scores[key]
    //         if(parseInt(key) !== taruid) continue
    //         let scoreArray = hisObj.scores
    //
    //         let totalScore = 0
    //         for(let i=0;i<scoreArray.length;i++){
    //             let num = scoreArray[i]
    //             totalScore += num
    //         }
    //
    //         return totalScore + this.baseScore
    //     }
    //
    //     return 0
    // }

    // getAvatarOriginScore(){
    //     return this.info.r_top * 80 + this.score
    // }

    onPrize(data){
        super.onPrize(data)

        let prize1 = this.prize[0].coin
        let prize2 = this.prize[1] ? this.prize[1].coin : 0
        cc.find("Canvas/UIManager").emit("ui_update_top_info_prize",prize1,prize2)
    }
}